package com.hulu73.shiro.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.hulu73.shiro.dao.UserDao;
import com.hulu73.shiro.entity.UserEntity;

@Controller
@RequestMapping("/a")
public class AdminController {

	@Autowired
	private UserDao userDao;
	
	/**
	 * 进入登录页
	 * @param httpServletRequest
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/login", method = RequestMethod.GET)
	public  String toLogin(HttpServletRequest httpServletRequest,Model model){
		
		return "/a/login";
	}
	
	/**
	 * 登录
	 * @param httpServletRequest
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/login", method = RequestMethod.POST)
	public  String login(String username, String password,Model	model){
		 UsernamePasswordToken token = new UsernamePasswordToken(username, password);  
		 Subject subject = SecurityUtils.getSubject();  
		
		  String  error=null;
	        try {  
	            subject.login(token);  
	        } catch (UnknownAccountException e) {  
	            error = "用户名/密码错误";  
	        } catch (IncorrectCredentialsException e) {  
	            error = "用户名/密码错误";  
	        } catch (AuthenticationException e) {  
	            //其他错误，比如锁定，如果想单独处理请单独catch处理  
	            error = "其他错误：" + e.getMessage();  
	        }  
	        if(StringUtils.isNotEmpty(error)) {//出错了，返回登录页面  
	        	model.addAttribute("error", error);  
	        	return	"/a/login";
	        } else {//登录成功  
	        	UserEntity user = (UserEntity)subject.getPrincipals().getPrimaryPrincipal();
	        	model.addAttribute("user", user);
	        	return	"/f/index";
	        } 
	}

	
	@RequestMapping(value="/logout")
	public  String logout(Model	model){
		 SecurityUtils.getSubject().logout();  
		 model.addAttribute("error", "退出成功");  
     	return	"/a/login";
	}
	
}
